﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;

namespace PeteBrown.ConferenceTrivia.Services
{
    public class TriviaClientService
    {
        private ObservableCollection<QuestionAndAnswer> _triviaItems = new ObservableCollection<QuestionAndAnswer>();
        public ObservableCollection<QuestionAndAnswer> TriviaItems
        {
            get { return _triviaItems; }
        }

        public event EventHandler TriviaLoaded;
        public void LoadTrivia()
        {
            string address = GetProxyEndpointAddress();

            TriviaServiceClient client = new TriviaServiceClient("CustomBinding_TriviaService", address);

            client.GetTriviaCompleted += (s, e) =>
            {

                // randomize the order of the trivia questions
                Random rand = new Random();
                var randomizedList = from QuestionAndAnswer item in e.Result
                                     orderby rand.Next()
                                     select item;

                foreach (QuestionAndAnswer i in randomizedList)
                {
                    _triviaItems.Add(i);
                }

                if (TriviaLoaded != null)
                    TriviaLoaded(this, EventArgs.Empty);

            };

            client.GetTriviaAsync();
        }


        // assumes app is hosted in ClientBin and the services folder is parallel to ClientBin
        private string GetProxyEndpointAddress()
        {
            Uri serviceUri = new Uri(App.Current.Host.Source, "../Services/TriviaService.svc");

            return serviceUri.ToString();
        }

    }
}
